package com.zrc.japktool.ui.view;

import javafx.application.Platform;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;  // 改为使用TextArea
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.KeyCode;
import javafx.scene.paint.Color;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;

public class LogTextField2 extends ScrollPane {
    // 日志级别枚举（颜色+前缀）
    public enum LogLevel {
        DEBUG(Color.GRAY, "[DEBUG]"),
        INFO(Color.BLACK, "[INFO]"),
        WARN(Color.ORANGE, "[WARN]"),
        ERROR(Color.RED, "[ERROR]");

        private final Color color;
        private final String prefix;

        LogLevel(Color color, String prefix) {
            this.color = color;
            this.prefix = prefix;
        }

        public Color getColor() {
            return color;
        }

        public String getPrefix() {
            return prefix;
        }
    }

    // 核心：使用TextArea替代TextField，支持多行和自动换行
    private TextArea logArea;  // 改为TextArea
    // 存储所有日志条目（用于拼接文本和修剪行数）
    private List<LogEntry> logEntries = new ArrayList<>();
    private Set<LogLevel> enabledLevels = EnumSet.allOf(LogLevel.class);
    private final SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private int maxLogLines = 1000;
    private boolean autoScroll = true; // 自动滚动开关（默认开启）

    public LogTextField2() {
        initStyle();
        initCopySupport();
        initAutoScroll();
    }

    /**
     * 初始化基础样式：单个TextArea + 滚动面板
     */
    private void initStyle() {
        // 1. 初始化TextArea（支持多行和自动换行）
        logArea = new TextArea();  // 实例化TextArea
        logArea.setEditable(false); // 禁止编辑
        logArea.setFocusTraversable(true); // 允许获取焦点
        logArea.setWrapText(true); // TextArea支持自动换行（此方法存在）
        logArea.setPrefHeight(Double.MAX_VALUE);
        logArea.setMaxWidth(Double.MAX_VALUE);
        logArea.setStyle(
                "-fx-background-color: transparent; " +
                        "-fx-border-width: 0; " +
                        "-fx-font-family: 'Microsoft YaHei', 'SimSun'; " +
                        "-fx-font-size: 12px; " +
                        "-fx-padding: 8;"
        );

        // 2. 配置滚动面板
        setContent(logArea);  // 关联TextArea到滚动面板
        setFitToWidth(true);
        setFitToHeight(true);
    }

    /**
     * 初始化自动滚动
     */
    private void initAutoScroll() {
        // 监听TextArea的文本变化
        logArea.textProperty().addListener((obs, oldText, newText) -> {
            if (autoScroll && !newText.isEmpty()) {
                Platform.runLater(() -> {
                    // 将光标定位到末尾实现滚动
                    logArea.positionCaret(newText.length());
                    setVvalue(1.0);
                });
            }
        });
    }

    /**
     * 初始化复制功能
     */
    private void initCopySupport() {
        logArea.setFocusTraversable(true);

        logArea.setOnKeyPressed(event -> {
            if (event.isControlDown() && event.getCode() == KeyCode.C) {
                String selectedText = logArea.getSelectedText();
                if (selectedText != null && !selectedText.isEmpty()) {
                    Clipboard clipboard = Clipboard.getSystemClipboard();
                    ClipboardContent content = new ClipboardContent();
                    content.putString(selectedText);
                    clipboard.setContent(content);
                }
            } else if (event.getCode() == KeyCode.ESCAPE) {
                logArea.deselect();
            }
        });

        logArea.setOnMouseClicked(event -> logArea.requestFocus());
    }

    /**
     * 添加日志
     */
    public void addLog(LogLevel level, String message) {
        if (!enabledLevels.contains(level)) return;

        Platform.runLater(() -> {
            String time = timeFormatter.format(new Date());
            String logContent = String.format("[%s] %s %s", time, level.getPrefix(), message);
            logEntries.add(new LogEntry(level, logContent));

            trimExcessLogs();

            // 拼接所有日志
            StringBuilder allLogs = new StringBuilder();
            for (LogEntry entry : logEntries) {
                allLogs.append(entry.content).append("\n");
            }
            if (allLogs.length() > 0) {
                allLogs.setLength(allLogs.length() - 1);
            }

            logArea.setText(allLogs.toString());  // 更新TextArea内容
        });
    }

    /**
     * 修剪日志行数
     */
    private void trimExcessLogs() {
        while (logEntries.size() > maxLogLines) {
            logEntries.remove(0);
        }
    }

    // ------------------- 对外暴露的控制方法 -------------------
    public void clearLogs() {
        logEntries.clear();
        logArea.setText("");  // 清空TextArea
        setVvalue(0.0);
    }

    public void setEnabledLevels(Set<LogLevel> enabledLevels) {
        this.enabledLevels = enabledLevels != null ? enabledLevels : EnumSet.allOf(LogLevel.class);
    }

    public void setMaxLogLines(int maxLogLines) {
        this.maxLogLines = Math.max(maxLogLines, 100);
        trimExcessLogs();
        refreshLogs();
    }

    public void setAutoScroll(boolean autoScroll) {
        this.autoScroll = autoScroll;
        if (autoScroll) {
            Platform.runLater(() -> {
                logArea.positionCaret(logArea.getText().length());
                setVvalue(1.0);
            });
        }
    }

    private void refreshLogs() {
        StringBuilder allLogs = new StringBuilder();
        for (LogEntry entry : logEntries) {
            allLogs.append(entry.content).append("\n");
        }
        if (allLogs.length() > 0) {
            allLogs.setLength(allLogs.length() - 1);
        }
        logArea.setText(allLogs.toString());  // 刷新TextArea内容
    }

    // 快捷添加日志的方法
    public void debug(String msg) {
        addLog(LogLevel.DEBUG, msg);
    }

    public void info(String msg) {
        addLog(LogLevel.INFO, msg);
    }

    public void warn(String msg) {
        addLog(LogLevel.WARN, msg);
    }

    public void error(String msg) {
        addLog(LogLevel.ERROR, msg);
    }

    /**
     * 内部类：存储单条日志的级别和内容
     */
    private static class LogEntry {
        LogLevel level;
        String content;

        LogEntry(LogLevel level, String content) {
            this.level = level;
            this.content = content;
        }
    }
}
